<?php
/**
 * Created by PhpStorm.
 * User: boye009
 * Date: 2016/2/27
 * Time: 10:18
 */

namespace Api\Domain;

use Shop\Api\FavoritesApi;
use Shop\Api\ProductApi;
use Shop\Api\ProductFaqApi;
use Shop\Api\ProductGroupApi;
use Shop\Api\ProductSkuApi;
use Common\Api\AccountApi;
use Shop\Model\ProductFaqModel;
use Shop\Model\ProductModel;
use Shop\Api\CategoryApi;
use Ucenter\Api\MemberApi;
use Uclient\Api\UserApi;

class ProductDomain extends BaseDomain{

    protected $business_code = "product";

    protected $allowType = array("json", "rss", "html");


    private $cate;

    /**
     * 分页查询
     * name:名称（模糊查询）(选填)
     * pageNo:当前页
     * pageSize:显示个数
     * cate_id商品分类ID(选填)
     */
    public function query(){
        $notes = "应用".$this->client_id."，调用商品分页查询接口";
        addLog("Product/query",$_GET,$_POST,$notes);

        $cate_parent = $this->_post("cate_parent",0);
        $name = $this -> _post('name',0);
        $cate_id= $this->_post("cate_id",0);
        $pageNo = $this->_post("page_no",1);
        $pageSize = $this->_post("page_size",10);
        $order = $this -> _post('order',ProductModel::SORT_COMPREHENSIVE);
        $min_cost = $this -> _post('min_cost',0.0);
        $max_cost = $this -> _post('max_cost',0.0);

        $this -> cate = array();

        if($name !== 0 && $name === ""){
            $this -> apiReturnSuc(array('count'=>0,'list'=>null));
        }

        $flag = 0;

        if($cate_parent != 0){
            if($cate_id == 0){
                $res = $this -> queryChild($cate_parent);
            }else{
                $res = $this -> queryChild($cate_id);
            }
            $flag = 1;
        }

        if($flag == 1 && (!$res['status'])){
            $this -> apiReturnErr($res['info']);
        }

        $map=array(
            'onshelf'=>1,   //已上架的产品
            'status'=>1,
        );
        if($flag == 1){
            $map['cate_id'] = array('in',$this -> cate);
        }

        if($name!=""){
            $map['name'] = array('like','%'.$name.'%');
        }

        if($max_cost!=0.0){
            $map['price'] = array(
                array('egt',$min_cost),
                array('elt',$max_cost),
            );
        }


        if($order == ProductModel::SORT_COMPREHENSIVE){
            $order = false;
        }else if($order == ProductModel::SORT_PRICE_ASC){
            $order = "price asc";
        }else if($order == ProductModel::SORT_PRICE_DESC){
            $order = "price desc";
        }else if($order == ProductModel::SORT_SALE){
            $order = "total_sales desc";
        }

        $page = array('curpage'=>$pageNo,'size'=>$pageSize); //分页产品

        $field = "id,name,total_sales,cate_id,img,price";

        $result=apiCall(ProductApi::QUERY_WITH_COUNT,array($map,$page,$order,$map,$field));

        if($result['status']){
            if(is_array($result['info']['list'])){
                foreach($result['info']['list'] as $k => $vo){
                    $result['info']['list'][$k]['img'] = getImageUrl($vo['img']);
                }

            }


            $this->apiReturnSuc($result['info']);
        }else{
            $this->apiReturnErr("暂无商品");
        }
    }

    public function queryByGroup(){

        $notes = "应用" . $this->client_id ."调用商品按分组查询接口接口";
        addLog("Product/queryByGroup", $_GET, $_POST, $notes);
        $this->checkVersion(100);


        if(IS_POST){

            $group_id = $this -> _post('group_id',0,'商品分组id缺失');
            $cate_id = $this -> _post('cate_id',0);
            $page_no = $this -> _post('page_no',1);
            $page_size = $this -> _post('page_size',10);
            $order = $this -> _post('order',ProductModel::SORT_COMPREHENSIVE);

            $map = array(
                'g_id' => $group_id,
                'status' => 1,//未删除
                'onshelf' => 1,//已上架
            );
            //时间限制
            $map['start_time'] = array('elt',time());
            $map['end_time'] = array('egt',time());

            if($cate_id != 0){
                $this -> cate =array();

                $res = $this->queryChild($cate_id);

                if(!$res['status']){
                    $this -> apiReturnErr($res['info']);
                }

                $map['cate_id'] = array('in',$this -> cate);
            }


            if($order == ProductModel::SORT_COMPREHENSIVE){
                $order = false;
            }else if($order == ProductModel::SORT_START_TIME_ASC){
                $order = "start_time asc";
            }else if($order == ProductModel::SORT_START_TIME_DESC){
                $order = "start_time desc";
            }else if($order == ProductModel::SORT_END_TIME_ASC){
                $order = "end_time asc";
            }else if($order == ProductModel::SORT_END_TIME_DESC){
                $order = "end_time desc";
            }

            $page = array('curpage'=>$page_no,'size'=>$page_size); //分页产品

            $field = "p_id as id,name,img,sku.price,start_time,end_time";

            $result = apiCall(ProductGroupApi::QUERY_WITH_PRODUCT,array($map,$page,$order,false,$field));

            if($result['status']){

                if(is_array($result['info']['list'])){
                    foreach($result['info']['list'] as $k => $vo){
                        $result['info']['list'][$k]['img'] = getImageUrl($vo['img']);
                    }

                }

                $this -> apiReturnSuc($result['info']);
            }else{
                $this -> apiReturnErr($result['info']);
            }

        }

    }

    public function queryFaq(){

        $notes = "应用" . $this->client_id ."调用查询商品咨询接口";
        addLog("Product/queryFaq", $_GET, $_POST, $notes);
        $this->checkVersion(100);

        if(IS_POST){
            $pid = $this -> _post('pid','','pid不能为空');
            $page_no = $this -> _post('page_no',1);
            $page_size = $this -> _post('page_size',10);

            $map = array(
                'pid' => $pid,
            );

            $page = array('curpage'=>$page_no,'size'=>$page_size);

            $order = "ask_time desc,reply_time desc";

            $result = apiCall(ProductFaqApi::QUERY_WITH_COUNT,array($map,$page,$order));
            if($result['status']){
                foreach($result['info']['list'] as &$vo){
                    $res = apiCall(MemberApi::GET_INFO,array(array('uid'=>$vo['ask_uid'])));
                    if(!$res['status']){
                        $this -> apiReturnErr($res['info']);
                    }else{
                        if($res['info'] == ""){
                            $vo['ask_nickname'] = "未知用户";
                        }else{
                            $vo['ask_nickname'] = $res['info']['nickname'];
                        }
                    }
                }
                $this -> apiReturnSuc($result['info']);
            }else{
                $this -> apiReturnErr($result['info']);
            }

        }

    }

    public function ask(){
        $notes = "应用" . $this->client_id ."调用商品咨询接口";
        addLog("Product/ask", $_GET, $_POST, $notes);
        $this->checkVersion(100);

        if(IS_POST){
            $pid = $this -> _post('pid','','pid不能为空');
            $ask_content = $this -> _post('ask_content','','询问内容不能为空');
            $ask_uid = $this -> _post('ask_uid','','用户id不能为空');
            $ask_username = $this -> _post('ask_username','','用户名不能为空');

            $map = array(
                'id' => $ask_uid,
                'username' => $ask_username,
            );
            $result = apiCall(UserApi::FIND,array($map));
            if($result['status']){
                if(is_null($result['info'])){
                    $this -> apiReturnErr('用户资料不符');
                }
            }else{
                $this -> apiReturnErr($result['info']);
            }

            $entity = array(
                'pid' => $pid,
                'ask_content' => $ask_content,
                'ask_uid' => $ask_uid,
                'ask_username' => $ask_username,
                'ask_time' => time(),
                'reply_content' => "",
                'reply_uid' => 0,
                'reply_username' => "",
                'reply_time' => 0,
            );
            $result = apiCall(ProductFaqApi::ADD,array($entity));
            if($result['status']){
                $this -> apiReturnSuc("资讯已提交！请耐心等待回复");
            }else{
                $this -> apiReturnErr($result['info']);
            }

        }

    }

    public function getFavorites(){

        $notes = "应用" . $this->client_id ."调用分页查询收藏商品接口";
        addLog("Product/getFavorites", $_GET, $_POST, $notes);
        $this->checkVersion(100);

        if(IS_POST){

            $type = 1;//主题帖

            $uid = $this -> _post('uid',0,'用户id缺失');
            $page_no = $this -> _post('page_no',1);
            $page_size = $this -> _post('page_size',10);

            $page = array(
                'curpage'=>$page_no,
                'size'=>$page_size,
            );

            $map = array(
                'itboye_favorites.uid' => $uid,
                'itboye_favorites.type' => $type,
            );

            $result = apiCall(FavoritesApi::QUERY_PRODUCT_WITH_COUNT,array($map,$page));

            if($result['status']){

                foreach($result['info']['list'] as $k => $v){

                    $result['info']['list'][$k]['img_url'] = getImageUrl($v['img_id']);

                }
                $this -> apiReturnSuc($result['info']);
            }else{
                $this -> apiReturnErr($result['info']);
            }

        }

    }

    /**
     * 收藏、取消收藏
     */
    public function favorites(){

        $notes = "应用" . $this->client_id ."调用收藏商品接口";
        addLog("Product/favorites", $_GET, $_POST, $notes);
        $this->checkVersion(100);

        if(IS_POST){

            $type = 1;

            $uid = $this -> _post('uid',0,'用户id缺失!');

            $favorite_id = $this -> _post('product_id',0,'商品id缺失!');

            $result = apiCall(ProductApi::GET_INFO,array(array('id' => $favorite_id)));
            if($result['status']){
                if($result['info']['status']==-1 || $result['info']['onshelf']==0){
                    $this -> apiReturnErr('商品id参数错误!');
                }
            }else{
                $this -> apiReturnErr($result['info']);
            }

            $favorite_value = $this -> _post('favorite_value',-1,'favorite_value参数缺失!');

            $map = array(
                'uid' => $uid,
                'favorite_id' => $favorite_id,
                'type' => $type,
            );

            $result = apiCall(FavoritesApi::GET_INFO,array($map));
            if(!$result['status']){
                $this -> apiReturnErr($result['info']);
            }

            if($favorite_value == 1){
                if(!is_null($result['info'])){
                    //已经存在收藏信息
                    $this -> apiReturnErr('该收藏已存在!');
                }
                $favorite_content = json_encode($this->getContent($favorite_id));//获取商品详情形成json
                $entity = array(
                    'uid' => $uid,
                    'type' => $type,
                    'favorite_id' => $favorite_id,
                    'favorite_content' => $favorite_content,
                    'create_time' => time(),
                );
                $result = apiCall(FavoritesApi::ADD,array($entity));
                if($result['status']){
                    $this -> apiReturnSuc($result['info']);//返回id
                }else{
                    $this -> apiReturnErr($result['info']);
                }

            }else if($favorite_value == 0){
                if(is_null($result['info'])){
                    //不存在收藏信息
                    $this -> apiReturnErr('不存在该收藏信息!');
                }
                $id = $result['info']['id'];
                $map = array(
                    'id' => $id,
                );
                $result = apiCall(FavoritesApi::DELETE,array($map));
                if($result['status']){
                    $this -> apiReturnSuc('取消收藏成功！');
                }else{
                    $this -> apiReturnErr($result['info']);
                }
            }else{
                $this -> apiReturnErr("favorite_value参数错误!");
            }

        }
    }



    public function detail(){

        $notes = "应用" . $this->client_id ."调用商品详情接口";
        addLog("Product/detail", $_GET, $_POST, $notes);
        $this->checkVersion(100);

        if(IS_POST){

            $id = $this -> _post('id',0,'商品id缺失');

            $uid = $this -> _post('uid',0);

            $result = apiCall(ProductApi::DETAIL,array($id));

            if($result['status']){
                if($result['info']['status']==-1 || $result['info']['onshelf']==0){
                    $this -> apiReturnErr('商品id参数错误');
                }
                //清除不用字段
                unset($result['info']['uid']);
                unset($result['info']['loc_country']);
                unset($result['info']['loc_province']);
                unset($result['info']['loc_city']);
                unset($result['info']['loc_address']);
                unset($result['info']['createtime']);
                unset($result['info']['updatetime']);
                unset($result['info']['onshelf']);
                unset($result['info']['status']);
                unset($result['info']['weight']);
                unset($result['info']['synopsis']);
                unset($result['info']['dt_origin_country']);
                unset($result['info']['_price']);
                unset($result['info']['dt_goods_unit']);
                unset($result['info']['pid']);
                unset($result['info']['detail']);

                $has_sku = apiCall(ProductSkuApi::HAS_SKU,array( $id ));

                if($has_sku['status']){
                    //0为统一规格,1为多规格
                    $has_sku = $has_sku['info'];
                }else{
                    $this -> apiReturnErr($has_sku['info']);
                }
                $result['info']['has_sku'] = $has_sku;

                if($has_sku == 1){
                    //多规格传值
                    //规格id
                    $skuId = apiCall(ProductSkuApi::GET_SKU_ID,array( $id , 'sku_id' ));
                    if($skuId['status']){
                        $result['info']['sku_id'] = json_decode($skuId['info']);
                    }else{
                        $this -> apiReturnErr($skuId['info']);
                    }
                    //规格名称
                    $skuName = apiCall(ProductSkuApi::GET_SKU_NAME,array( $id , 'sku_desc' ));
                    if($skuName['status']){
                        $result['info']['sku_name'] = json_decode($skuName['info']);
                    }else {
                        $this->apiReturnErr($skuName['info']);
                    }
                    //规格详细信息
                    $skulist = apiCall(ProductSkuApi::QUERY_NO_PAGING,array(array('product_id' => $id)));
                    $min_ori_price = 1e18;
                    $min_price = 1e18;
                    $max_price = 0.0;
                    $max_ori_price = 0.0;
                    if($skulist['status']){
                        $result['info']['sku_list'] = $skulist['info'];
                        foreach($skulist['info'] as $vo){
                            if($vo['ori_price'] < $min_ori_price){
                                $min_ori_price = $vo['ori_price'];
                            }
                            if($vo['ori_price'] > $max_ori_price){
                                $max_ori_price = $vo['ori_price'];
                            }
                            if($vo['price'] < $min_price){
                                $min_price = $vo['price'];
                            }
                            if($vo['price'] > $max_price){
                                $max_price = $vo['price'];
                            }
                        }
                        $result['info']['min_price'] = $min_price;
                        $result['info']['min_ori_price'] = $min_ori_price;
                        $result['info']['max_price'] = $max_price;
                        $result['info']['max_ori_price'] = $max_ori_price;
                    }else{
                        $this -> apiReturnErr($skulist['info']);
                    }

                }else{
                    $skulist = apiCall(ProductSkuApi::GET_INFO,array(array('product_id' => $id)));
                    if($skulist['status']){
                        unset($skulist['info']['sku_id']);
                        unset($skulist['info']['sku_desc']);
                        unset($skulist['info']['createtime']);
                        unset($skulist['info']['icon_url']);
                        $result['info']['sku_info'] = $skulist['info'];
                        $result['info']['min_ori_price'] = $skulist['info']['ori_price'];
                        $result['info']['min_price'] = $skulist['info']['price'];
                    }else{
                        $this -> apiReturnErr($skulist['info']);
                    }
                }

                $group = apiCall(ProductGroupApi::GET_GROUP_BY_ID,array($id));
                if(!$group['status']){
                    $this -> apiReturnErr($group['info']);
                }
                $result['info']['group'] = $group['info'];

                $result['info']['favorite'] = 0;
                if($uid != 0){
                    $map = array(
                        'favorite_id' => $id,
                        'uid' => $uid,
                    );
                    $favorite = apiCall(FavoritesApi::COUNT,array($map));
                    if($favorite['status']){
                        if($favorite['info']>0){
                            $result['info']['favorite'] = 1;
                        }
                    }else{
                        $this -> apiReturnErr($favorite['info']);
                    }
                }

                if(is_null($result['info']['group'])){
                    unset($result['info']['group']);
                }

                //处理图片
                $result['info']['main_img'] = getImageUrl($result['info']['main_img']);
                if(is_array($result['info']['imgs'])){
                    foreach($result['info']['imgs'] as $k => $v){
                        $result['info']['imgs'][$k] = getImageUrl($v);
                    }
                }
                if($has_sku == 1 && is_array($result['info']['sku_list'])){
                    foreach($result['info']['sku_list'] as $k => $v){
                        $result['info']['sku_list'][$k]['icon_url'] = getImageUrl($v['icon_url']);
                    }
                }

                $this -> apiReturnSuc($result['info']);
            }else{
                $this -> apiReturnErr($result['info']);
            }

        }

    }

    /**
     * 私有方法
     * @param $id
     */

    private function getContent($id)
    {
        $result = apiCall(ProductApi::DETAIL, array($id));

        if ($result['status']) {
            if ($result['info']['status'] == -1 || $result['info']['onshelf'] == 0) {
                $this->apiReturnErr('商品id参数错误');
            }
            //清除不用字段
            unset($result['info']['uid']);
            unset($result['info']['loc_country']);
            unset($result['info']['loc_province']);
            unset($result['info']['loc_city']);
            unset($result['info']['loc_address']);
            unset($result['info']['createtime']);
            unset($result['info']['updatetime']);
            unset($result['info']['onshelf']);
            unset($result['info']['status']);
            unset($result['info']['store_id']);
            unset($result['info']['weight']);
            unset($result['info']['synopsis']);
            unset($result['info']['dt_origin_country']);
            unset($result['info']['_price']);
            unset($result['info']['dt_goods_unit']);
            unset($result['info']['pid']);
            unset($result['info']['detail']);

            $has_sku = apiCall(ProductSkuApi::HAS_SKU, array($id));

            if ($has_sku['status']) {
                //0为统一规格,1为多规格
                $has_sku = $has_sku['info'];
            } else {
                $this->apiReturnErr($has_sku['info']);
            }
            $result['info']['has_sku'] = $has_sku;

            if($has_sku == 1){
                //多规格传值
                //规格id
                $skuId = apiCall(ProductSkuApi::GET_SKU_ID,array( $id , 'sku_id' ));
                if($skuId['status']){
                    $result['info']['sku_id'] = json_decode($skuId['info']);
                }else{
                    $this -> apiReturnErr($skuId['info']);
                }
                //规格名称
                $skuName = apiCall(ProductSkuApi::GET_SKU_NAME,array( $id , 'sku_desc' ));
                if($skuName['status']){
                    $result['info']['sku_name'] = json_decode($skuName['info']);
                }else {
                    $this->apiReturnErr($skuName['info']);
                }
                //规格详细信息
                $skulist = apiCall(ProductSkuApi::QUERY_NO_PAGING,array(array('product_id' => $id)));
                $min_ori_price = 1e18;
                $min_price = 1e18;
                $max_price = 0.0;
                $max_ori_price = 0.0;
                if($skulist['status']){
                    $result['info']['sku_list'] = $skulist['info'];
                    foreach($skulist['info'] as $vo){
                        if($vo['ori_price'] < $min_ori_price){
                            $min_ori_price = $vo['ori_price'];
                        }
                        if($vo['ori_price'] > $max_ori_price){
                            $max_ori_price = $vo['ori_price'];
                        }
                        if($vo['price'] < $min_price){
                            $min_price = $vo['price'];
                        }
                        if($vo['price'] > $max_price){
                            $max_price = $vo['price'];
                        }
                    }
                    $result['info']['min_price'] = $min_price;
                    $result['info']['min_ori_price'] = $min_ori_price;
                    $result['info']['max_price'] = $max_price;
                    $result['info']['max_ori_price'] = $max_ori_price;
                }else{
                    $this -> apiReturnErr($skulist['info']);
                }

            }else{
                $skulist = apiCall(ProductSkuApi::GET_INFO,array(array('product_id' => $id)));
                if($skulist['status']){
                    unset($skulist['info']['sku_id']);
                    unset($skulist['info']['sku_desc']);
                    unset($skulist['info']['createtime']);
                    unset($skulist['info']['icon_url']);
                    $result['info']['sku_list'] = $skulist['info'];
                    $result['info']['min_ori_price'] = $skulist['info']['ori_price'];
                    $result['info']['min_price'] = $skulist['info']['price'];
                }else{
                    $this -> apiReturnErr($skulist['info']);
                }
            }

            $group = apiCall(ProductGroupApi::GET_GROUP_BY_ID,array($id));
            if(!$group['status']){
                $this -> apiReturnErr($group['info']);
            }
            $result['info']['group'] = $group['info'];

            $result['info']['favorite'] = 0;

            return $result['info'];

        } else {
            $this->apiReturnErr($result['info']);
        }

    }

    /**
     * 循环版本
     * @param $id
     * @return array
     */
    private function queryChild($id){
        $que = array();
        array_push($que,$id);
        while(count($que)!=0){
            $tmp = array_shift($que);
            $map = array(
                'parent' => $tmp,
            );
            $result = apiCall(CategoryApi::QUERY_NO_PAGING,array(array($map)));

            if($result['status']){
                if(is_array($result['info'])){
                    foreach($result['info'] as $val){
                        array_push($que,$val['id']);
                    }
                }else{
                    array_push($this -> cate , $tmp );
                }
            }else{
                return array('status' => false,'info' => $result['info']);
            }
        }
        return array('status' => true,'info' => $this -> cate);
    }

    /**
     * 递归版本
     */
    /*private function queryChild($id){

        $map = array(
            'parent'=>$id,
        );
        $result = apiCall(CategoryApi::QUERY_NO_PAGING,array(array($map)));

        if($result['status']){

            if(is_array($result['info'])){
                foreach($result['info'] as $val){
                    $this->queryChild($val['id']);
                }
            }else{
                array_push($this->cate,$id);
            }

        }


    }*/

}